'use client'

import React, { useEffect, useState } from 'react'
import { UniverProvider, useUniver } from '@/components/univer/UniverProvider'
import { CollaborativeUser, Sheet, Cell } from '@/types/sheet'
import { cn } from '@/lib/utils'

interface UniverSpreadsheetProps {
  sheet?: Sheet
  cells?: Cell[]
  onCellUpdate?: (row: number, column: number, value: string, formula?: string) => void
  onStyleUpdate?: (row: number, column: number, style: any) => void
  onSave?: (cells: Cell[]) => void
  collaborativeUsers?: CollaborativeUser[]
  onCursorUpdate?: (row: number, column: number) => void
  allowEdit?: boolean
}

const UniverSpreadsheetContent: React.FC<UniverSpreadsheetProps> = ({
  sheet,
  cells = [],
  onCellUpdate,
  onStyleUpdate,
  onSave,
  collaborativeUsers = [],
  onCursorUpdate,
  allowEdit = true
}) => {
  const { univerAPI, isReady } = useUniver()
  const [isLoading, setIsLoading] = useState(true)
  const [workbookId, setWorkbookId] = useState<string>('')
  const [isWorkbookCreated, setIsWorkbookCreated] = useState(false)

  useEffect(() => {
    console.log('UniverSpreadsheet useEffect triggered:', { isReady, univerAPI: !!univerAPI, sheet: !!sheet })
    
    if (isReady && univerAPI && !isWorkbookCreated) {
      setIsLoading(false)
      
      // 创建或更新工作簿
      const newWorkbookId = sheet ? `workbook-${sheet.id}` : 'default-workbook'
      setWorkbookId(newWorkbookId)
      
      // 将cells数据转换为Univer格式
      const cellData: Record<string, Record<string, any>> = {}
      
      // 确保即使cells为空也能正常显示表格
      if (cells && cells.length > 0) {
        cells.forEach(cell => {
          const rowKey = cell.row.toString()
          const colKey = cell.column.toString()
          
          if (!cellData[rowKey]) {
            cellData[rowKey] = {}
          }
          
          cellData[rowKey][colKey] = {
            v: cell.value || '',
            f: cell.formula || undefined,
            s: cell.style ? (typeof cell.style === 'string' ? JSON.parse(cell.style) : cell.style) : undefined
          }
        })
      }

      // 创建或更新工作簿
      try {
        univerAPI.createWorkbook({
          id: newWorkbookId,
          name: sheet?.title || 'Untitled Sheet',
          sheetOrder: ['sheet1'],
          locale: 'zh-CN',
          styles: {},
          sheets: {
            sheet1: {
              id: 'sheet1',
              name: 'Sheet1',
              cellData: cellData,
              rowCount: 1000,
              columnCount: 20,
              rowHeader: {
                width: 46,
                hidden: false
              },
              columnHeader: {
                height: 20,
                hidden: false
              },
              selections: ['A1'],
              rightToLeft: false
            }
          }
        })
        
        setIsWorkbookCreated(true)
        console.log('Univer workbook created/updated:', newWorkbookId)
      } catch (error) {
        console.error('Failed to create/update Univer workbook:', error)
        // 如果workbook已存在，也标记为已创建
        if (error instanceof Error && error.message && error.message.includes('same unit id')) {
          setIsWorkbookCreated(true)
        }
      }
    }
  }, [isReady, univerAPI, sheet, cells, isWorkbookCreated])

  // 当sheet变化时，重置workbook创建状态
  useEffect(() => {
    if (sheet) {
      setIsWorkbookCreated(false)
    }
  }, [sheet?.id])

  // 监听Univer的单元格变化
  useEffect(() => {
    if (isReady && univerAPI && workbookId && onCellUpdate) {
      // 这里应该监听Univer的单元格变化事件
      // 由于Univer API的复杂性，这里先提供一个基础实现
      console.log('Setting up Univer cell change listeners for workbook:', workbookId)
    }
  }, [isReady, univerAPI, workbookId, onCellUpdate])


  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">正在加载表格...</p>
        </div>
      </div>
    )
  }

  // 移除这个检查，允许在没有 sheet 时也显示表格
  // if (!sheet) {
  //   return (
  //     <div className="flex items-center justify-center h-96">
  //       <div className="text-center">
  //         <p className="text-gray-600 dark:text-gray-400">请选择一个表格</p>
  //       </div>
  //     </div>
  //   )
  // }

  return (
    <div className="flex flex-col h-full bg-white dark:bg-gray-900">
      {/* 协作状态栏 */}
      {collaborativeUsers.length > 0 && (
        <div className="flex items-center justify-between p-2 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                在线用户: {collaborativeUsers.length}
              </span>
              {collaborativeUsers.map(user => (
                <div
                  key={user.id}
                  className="flex items-center gap-1 px-2 py-1 rounded text-xs"
                  style={{ backgroundColor: user.color + '20', color: user.color }}
                >
                  <div
                    className="w-2 h-2 rounded-full"
                    style={{ backgroundColor: user.color }}
                  />
                  {user.name}
                </div>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-500 dark:text-gray-400">
              表格: {sheet?.title || 'Untitled Sheet'}
            </span>
          </div>
        </div>
      )}

      {/* Univer 表格容器 */}
      <div className="flex-1 relative" style={{ height: 'calc(100vh - 200px)' }}>
        <div id={`univer-container-${sheet?.id || 'default'}`} className="w-full h-full" />
      </div>
    </div>
  )
}

export const UniverSpreadsheet: React.FC<UniverSpreadsheetProps> = (props) => {
  return <UniverSpreadsheetContent {...props} />
}
